package com.jianan.mis.sys;

import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Tray;
import org.eclipse.swt.widgets.TrayItem;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;

/**
 * 系统托盘
 * 
 * @author hp
 * 
 */
public class SystemTray {
	private TrayItem trayItem; // 托盘项

	private Image trayImage; // 托盘图标

	public SystemTray() {
	}

	public void createSysTray(final IWorkbenchWindow window) {
		trayItem = initTrayItem(window); // 初始化托盘
		if (trayItem != null) {
			trayPopupMenu(window); // 弹出托盘菜单项
			trayMinimize(window); // 最小化窗口到托盘
		}
	}

	/**
	 * 单击最小化窗口按钮事件
	 * 
	 * @param shell
	 */
	public void windowMinimized(final Shell shell) {
		shell.setMinimized(true); // 最小化窗口
		shell.setVisible(false); // 窗口不可见
	}

	/**
	 * 最小化程序到托盘
	 * 
	 * @param window
	 */
	public void trayMinimize(final IWorkbenchWindow window) {
		window.getShell().addShellListener(new ShellAdapter() {
			public void shellIconified(ShellEvent e) {
				window.getShell().setVisible(false);
			}
		});
		trayItem.addListener(SWT.DefaultSelection, new Listener() {
			public void handleEvent(Event event) {
				Shell shell = window.getShell();
				if (!shell.isVisible()) {
					shell.setVisible(true);
					window.getShell().setMinimized(false);
				}
			}
		});
	}

	/**
	 * 托盘弹出菜单
	 * 
	 * @param window
	 */
	public void trayPopupMenu(final IWorkbenchWindow window) {
		trayItem.addListener(SWT.MenuDetect, new Listener() {
			public void handleEvent(Event event) {
				MenuManager trayMenu = new MenuManager();
				Menu menu = trayMenu.createContextMenu(window.getShell());
				fillTrayItem(trayMenu, window);
				menu.setVisible(true);
			}
		});
	}

	private void fillTrayItem(IMenuManager trayItem,
			final IWorkbenchWindow window) {
		Action exitSystem = new Action("退出系统[&E]", ImageManager
				.getImageDescriptor(IImageKeys.BRAND)) {
			public void run() {
				PlatformUI.getWorkbench().close();
			}
		};
		trayItem.add(exitSystem);
	}

	private TrayItem initTrayItem(IWorkbenchWindow window) {
		final Tray tray = window.getShell().getDisplay().getSystemTray();
		if (tray == null) {
			return null;
		}
		trayItem = new TrayItem(tray, SWT.NONE);
		trayImage = ImageManager.getImage(IImageKeys.BRAND);
		trayItem.setImage(trayImage);
		return trayItem;
	}

	public void dispose() {
		if (trayItem != null)
			trayItem.dispose();
	}
}
